﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Net;
using Communergy.NationalGridDataServices;
using System.Diagnostics;

namespace Communergy.NationalGridDataServices
{
    public class GridDataHelper
    {
        /// <summary>
        /// Gets the live carbon intensity as XML
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <returns></returns>
        public static string GetRemoteXml(string url)
        {
            string result = "";
            try
            {
                // Create the web request  
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                // Get response  
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream  
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    // Read the whole contents and return as a string  
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(string.Format("Error retrieving data from {0}.  Error: {1}", url, e.Message ));
                result = string.Format("Error: {0}", e.Message);
            }
            return result;
        }


        public static electricityCO2Item LiveCarbonIntensityFromXml(string liveCarbonIntensityXml)
        {
            XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(electricityCO2Item));
            try
            {
                electricityCO2Item liveCarbonIntensity = (electricityCO2Item)xSerializer.Deserialize(new StringReader(liveCarbonIntensityXml));
                return liveCarbonIntensity;
            }
            catch (Exception e)
            {
                Trace.WriteLine(string.Format("Error converting xml to object. Error: {0}, xml {1}, stack trace: {2}", e.Message, liveCarbonIntensityXml,e.StackTrace));
                return null;
            }
        }




        public static GENERATION_BY_FUEL_TYPE_TABLE GENERATION_BY_FUEL_TYPE_TABLEFromXml(string gENERATION_BY_FUEL_TYPE_TABLEXml)
        {
            XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(GENERATION_BY_FUEL_TYPE_TABLE));
            GENERATION_BY_FUEL_TYPE_TABLE liveCarbonIntensity = (GENERATION_BY_FUEL_TYPE_TABLE)xSerializer.Deserialize(new StringReader(gENERATION_BY_FUEL_TYPE_TABLEXml));
            return liveCarbonIntensity;
        }
    }
}
